<template>
  <a-spin :spinning="spinning">
    <div class="vh100 flex space_center align_items">
      <div class="login" v-show="isLogin">
        <dl class="fs20">
          <dt class="font_normal">扫一扫登录</dt>
          <dd>请使用i国网 <span>打印微应用</span> 扫码，获取PIN登录</dd>
        </dl>

        <div class="login_one flex space_center align_items">
          <div v-if="!error" class="login_code" id="qrcode" ref="qrCodeDiv" @click="handerClick('code')">
          </div>
          <div v-else class="login_code flex space_center align_items" style="background: #F6F6F6;">
            <div class="code_error flex flexc align_items">
              <div class="bj">
              </div>
              <p class="network_error">网络连接失败</p>
              <p class="refresh pointer" @click="handerClick('code')">点击刷新</p>
            </div>
          </div>
          <div class="login_pin">
            <a-input v-model:value="formState.pinCode" size="large" placeholder="请输入PIN码" />
            <a-button type="primary" size="large" block @click="login">登录</a-button>
            <a-button type="link" class="pos_right" @click="isLogin = fasle">去注册</a-button>
          </div>
        </div>
      </div>
      <div class="register" v-show="!isLogin">
        <a-form class="register_form" :model="formState.user" :rules="column.rules" labelAlign="right" :labelCol="{span: 5, pull: 1}" name="nest-messages" @finish="onFinish">
          <a-form-item name="printStationName" label="工作站名称">
            <a-input v-model:value="formState.user.printStationName" size="large" placeholder="请输入工作站名称" />
          </a-form-item>
          <a-form-item name="baseOrgName" label="所属组织">
            <span v-if="formState.user.baseOrgName">{{ formState.user.baseOrgName }}</span>
            <a-button v-else type="primary" size="large" @click="handerClick('organization')">选择组织</a-button>
          </a-form-item>
          <a-form-item name="printStationIp" label="本机IP">
            <a-input v-model:value="formState.user.printStationIp" size="large" placeholder="请输入本机IP地址" />
          </a-form-item>
          <a-form-item name="printStationPosition" label="本机位置">
            <a-input v-model:value="formState.user.printStationPosition" size="large" placeholder="请输入本机位置" />
          </a-form-item>
          <a-form-item class="submit">
            <a-button type="primary" size="large" html-type="submit">申请注册打印服务器</a-button>
            <a-button type="link" class="pos_right" @click="isLogin = true">去登录</a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </a-spin>
  <!-- 选择组织 -->
  <a-modal v-model:visible="organizationVisible" title="选择组织" @ok="handerClick('ok')">
    <a-tree
      :key="treeKey"
      v-model:selectedKeys="selectedKeys"
      v-model:checkedKeys="checkedKeys"
      checkable
      :checkStrictly="true"
      :field-names="fieldNames"
      :load-data="onLoadData"
      :tree-data="treeData"
    />
  </a-modal>
</template>

<script>
import QRCode from 'qrcodejs2'
import IP from 'ip'
import { message } from 'ant-design-vue';
import config from '@/config'
import column from './column'
import { randomRange, getTarget } from '@/utils'
import api from '@/api/login'
import api2 from '@/api/pint'
export default {
  data() {
    return {
      isLogin: true,
      spinning: false,
      organizationVisible: false,
      treeKey: 1,
      fieldNames: {
        children: 'children',
        title: 'name',
        key: 'id'
      },
      checkedKeys:[],
      selectedKeys:[],
      treeData:[],
      formState: {
        user: {
          printStationName: '',
          baseOrgName: '',
          baseOrgId: '',
          printStationIp: IP.address(),
          printStationPosition: ''
        },
        pin: '',
      },
      error: false,
      column: column
    }
  },
  methods: {
    //注册
    onFinish(values) {
      const postData = JSON.parse(JSON.stringify({...values,baseOrgId: this.formState.user.baseOrgId}))
      api.register(postData).then(res => {
        message.success('已注册，正在等待审核！');
        setTimeout(() => {
          this.isLogin = true
        }, 2000)
      })
    },
    //登录
    login() {
      const postData = JSON.parse(JSON.stringify({ pinCode: this.formState.pinCode }))
      this.spinning = true
      api.login(postData).then(res => {
        this.spinning = false
        localStorage.setItem('state', JSON.stringify(res.data))
        this.$store.commit('changeLoginStatus', true)
        this.$router.push({
          path: '/print'
        })
      }).catch(err => {
        this.spinning = false
      })
    },
    handerClick(type) {
      if (type === 'code') {
        this.createQRCode()
      }else if(type === 'organization'){
        this.organizationVisible = true
        this.onLoadData()
      }else if(type === 'ok'){
        let checkedKeys = this.checkedKeys.checked
        if(checkedKeys){
          if(checkedKeys.length === 1){
            let fil = getTarget(checkedKeys[0],this.treeData)
            this.formState.user.baseOrgName = fil.name
            this.formState.user.baseOrgId = fil.id
            this.organizationVisible = false
          }else{
            message.warning('只能选择一项！')
          }
        }else{
          message.warning('请选择所属组织！')
        }
      }
    },
    createQRCode() {
      if (!config.agentid || !IP.address()) {
        this.error = true
        return
      }
      let text = `zipapp://appid.${config.agentid}/index.html?type=1&ip=${IP.address()}&random=${randomRange(0, 30)}`;
      document.getElementById("qrcode").innerHTML = "";//为了防止生成多张，生成前先清空原先的；
      const qrcodeCreater = new QRCode(this.$refs.qrCodeDiv, {
        text: text,//二维码的内容undefined
        title: '',
        width: 170,//二维码的宽度
        height: 170,//二维码的高度
        colorDark: "#333333", //二维码颜色
        colorLight: "#ffffff", //二维码背景色
        correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
      });
      qrcodeCreater._el.title = ""; //隐藏title
      this.error = false
    },
    //异步加载组织
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode) {
          if (treeNode.dataRef.children) {
            resolve();
            return;
          }
          api2.organizationFramework({ orgId: treeNode.dataRef.id }).then(res => {
            treeNode.dataRef.children = res.data
            res.data.forEach(item => {
              item.isLeaf = false
              // item.isLeaf = !!!(item.isLeaf === 'N')
            });
            this.treeData = [...this.treeData];
            resolve();
          })
        } else {
          console.log('第一次触发onLoadData')
          this.treeData = []
          api2.organizationFramework({ orgId: '' }).then(res => {
            console.log(res.data)
            res.data.forEach(item => {
              // item.isLeaf = !!!(item.isLeaf === 'N')
              item.isLeaf = false
            });
            console.log(222,res.data)
            this.treeData = res.data
            resolve();
          })
        }
      });
    },
  },
  mounted() {
    this.createQRCode()
  },
  watch:{
    organizationVisible:{
      handler(val){
        this.treeKey ++
      }
    }
  }
}
</script>

<style lang="scss">
@import "./index.scss";
</style>